<template>
  <div class="update-photo">
    <img class="img" :src="img" ref="img">

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    // 预览图片地址信息
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 裁剪框不超过画布的范围
      dragMode: 'move', // 不能拖拽裁剪区，只能移动画布
      aspectRatio: 1, // 裁剪区的长宽比
      autoCropArea: 1, // 阻止移动裁剪区
      cropBoxMovable: false, //  阻止裁剪区的缩放
      cropBoxResizable: false, // 禁用背景
      background: true
    })
  },
  methods: {
    // 确定事件
    onConfirm() {
      // 基于服务端的裁切使用 getData 方法获取裁切参数
      // console.log(this.cropper.getData())
      // 纯客户端的裁切使用 getCroppedCanvas 获取裁切的文件对象
      this.cropper.getCroppedCanvas().toBlob(blob => {
        //  console.log(blob)  // 裁剪后的结果信息
        this.onUpdatePhoto(blob)
      })
    },
    async onUpdatePhoto(blob) {
      const formDate = new FormData()
      formDate.append('photo', blob)
      this.$toast.loading({
        message: '更新中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data } = await updateUserPhoto(formDate)
        //   console.log(data)
        this.$toast('更新头像成功！')
        this.$emit('update-photo', data.data.photo)
        this.$emit('close')
      } catch (error) {
        this.$toast('更新头像失败！')
      }
    }
  }
}
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel, .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
